<?php class HeatherDocument extends HeatherObject {
	const VERSION = 'AIRPORT';
	const SIGNATURE = '[^ I \s ARE \s (\p{L}+) \s CAT, \s THIS \s IS \s HEATHER \s THREAD $]ux';
	protected $Title = '';
	protected $State = 'Init';


	protected function NewSection (HeatherBlock $Header) {
		$this->AddChild (new HeatherSection ($Header));
	}
	protected function XMLAttributes () {
		$Result = '';
		strlen ($this->Title) and $Result .= ' Title="'.htmlspecialchars ($this->Title, ENT_QUOTES).'"';
		return ($Result);
	}


	public function AddString ($String) {
		$Repeat = 1;
		do {
			$Repeat -= 1;
			switch ($this->State) {
				case 'Init':
					$Matches = array ();
					if (preg_match (self::SIGNATURE, $String, $Matches)) {
						list ($Expected, $Found) = array (self::VERSION, $Matches [1]);
						$Expected === $Found or trigger_error ("version mismatch: expected [$Expected], found [$Found]; I will try my best, but don't expect anything perfect", E_USER_WARNING);
						$this->State = 'Head';
					} else {
						$this->State = 'Text';
						$Repeat = 1;
					}
				break;
				case 'Text':
					$Length = strlen ($Trimmed = trim ($String));
					if ($Length > 3 and str_pad ('', $Length, '=') === $Trimmed) {
						$this->NewSection ($this->PopBlock ());
					} else {
						if ($this->NoLastChild ()) $this->NewSection (new HeatherBlock ());
						call_user_func (array ($this->LastChild, __FUNCTION__), $String);
					}
				break;
				case 'Head':
					if (! $this->IsEmptyString ($String)) {
						$Matches = preg_split ('(\s)', $String, 2);
						count ($Matches < 2) and $Matches [1] = '';
						list ($Instruction, $Parameters) = $Matches;
						switch ($Instruction) {
							case 'TITLE':
								strlen ($this->Title) and $this->Title .= ' ';
								$this->Title .= trim ($Parameters);
							break;
							default: trigger_error ("ignoring unknown instruction [$Instruction]", E_USER_WARNING);
						}
					} else $this->State = 'Text';
				break;
				case 'Code':
var_dump ('code:'.$String);
				break;
				default: trigger_error ("unknown state [{$this->State}], not sure what to do", E_USER_ERROR);
			}
		} while ($Repeat);
	}

} ?>